#include "messagerouter.h"

std::string rootDir = "/home/nebulau/projects/ibed-server"; /*数据根目录*/

MessageQueue<RequestMessage> msgrout2authMQ;      /*消息路由线程发送给授权管理线程的消息队列*/
MessageQueue<RequestMessage> msgrout2serviceMQ;   /*消息路由线程发送给业务线程的消息队列*/
MessageQueue<ResponseMessage> process2responseMQ; /*各个处理线程发送给消息响应线程的消息队列*/

Any MessageRouter::run()
{
    Json::Reader reader;
    Json::Value router_table;

    /*读取路由表文件*/
    std::string router_table_str = read_file("../config/router_table.json");

    /*解析路由表*/
    if (reader.parse(router_table_str, router_table))
    {
        /*遍历每条路由配置*/
        for (int i = 0; i < router_table["router_table"].size(); i++)
        {
            /*路由GET请求*/
            if ("GET" == router_table["router_table"][i]["method"].asString())
            {
                svr.Get(router_table["router_table"][i]["path"].asString(), [this, &router_table, i](const httplib::Request &req, httplib::Response &res){
                    if("msgrout2authMQ" == router_table["router_table"][i]["mseeage_queue"].asString())
                    {
                        // RequestMessage reqMsg = {ReqType::STATIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
                        // msgrout2serviceMQ.push(reqMsg);
                    }
                    else if("msgrout2serviceMQ" == router_table["router_table"][i]["mseeage_queue"].asString())
                    {
                        // RequestMessage reqMsg = {ReqType::STATIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
                        // msgrout2serviceMQ.push(reqMsg);
                    }
                    else{}
                });
            }
            /*处理POST请求*/
            else if ("POST" == router_table["router_table"][i]["method"].asString())
            {
                if("msgrout2authMQ" == router_table["router_table"][i]["mseeage_queue"].asString())
                {
                    // RequestMessage reqMsg = {ReqType::STATIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
                    // msgrout2serviceMQ.push(reqMsg);
                }
                else if("msgrout2serviceMQ" == router_table["router_table"][i]["mseeage_queue"].asString())
                {
                    // RequestMessage reqMsg = {ReqType::STATIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
                    // msgrout2serviceMQ.push(reqMsg);
                }
                else{}
            }
            else
            {
                std::cout << "ERROR: router table NO." << i  << " unknow method" << std::endl;
            }
        }
    }

    /*错误的请求*/
    svr.set_error_handler([](const httplib::Request &req, httplib::Response &res)
                          { res.set_content("error uri: " + req.path, "text/plain"); });

    std::cout << "Server running on port 8081" << std::endl;
    svr.listen("0.0.0.0", 8081);

    return 0;
}

status MessageRouter::SendReqToAuth(httplib::Request req, httplib::Response &res)
{
    std::string seg1 = "";
    auto completion_promise = std::make_shared<std::promise<void>>();
    auto completion_future = completion_promise->get_future();

    /**
     * /                统一成 /static/html/index.html
     * /favicon.ico     统一成 /static/image/favicon.ico
     * */
    req.path = (req.path == "/") ? ("/static/html/index.html") : (req.path);
    req.path = (req.path == "/favicon.ico") ? ("/static/image/favicon.ico") : (req.path);

    /*将请求发送给业务处理线程*/
    if ("GET" == req.method)
    {
        if (req.path.rfind("/static", 0) == 0)
        {
            std::cout << "/static" << std::endl;
            RequestMessage reqMsg = {ReqType::STATIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
            msgrout2serviceMQ.push(reqMsg);
        }
        else if (req.path.rfind("/public", 0) == 0)
        {
            std::cout << "/public" << std::endl;
            RequestMessage reqMsg = {ReqType::PUBLIC, std::make_shared<httplib::Request>(req), &res, completion_promise};
            msgrout2serviceMQ.push(reqMsg);
        }
        else
        {
            res.set_content("Invalid Request", "text/plain");
            completion_promise->set_value();
        }
    }
    else if ("POST" == req.method)
    {
        std::cout << "POST" << std::endl;
        if (req.path.rfind("/register", 0) == 0)
        {
            std::cout << "/register" << std::endl;
            RequestMessage reqMsg = {ReqType::REGISTER, std::make_shared<httplib::Request>(req), &res, completion_promise};
            msgrout2authMQ.push(reqMsg);
        }
    }
    else
    {
        /*其余方法此处不做处理，上层逻辑已经处理*/
    }
    /*todo：应该做超时处理，以免出现授权线程未响应结果，而出现无法向客户端反馈响应的现象*/

    /*阻塞等待请求处理完成*/
    completion_future.wait();

    return SUCCESS;
};
